package com.xiaoda.controller;

import com.xiaoda.entity.JsonResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 上传管理
 */

@Controller
@CrossOrigin
@ResponseBody
public class UploadController {

    /**
     * 图片上传
     *
     * @param file    图片
     * @param request 请求
     * @return 返回结果
     */
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file, HttpServletRequest request) {
        JsonResult json = new JsonResult();
        String path = request.getServletContext().getRealPath("/images");
        String filename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(filename);
        String fileNewName = UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;

        File fe = new File(path);
        if (!fe.exists()) {
            fe.mkdir();
        }

        try {
            file.transferTo(new File(fe + "/" + fileNewName));
            json.setCode(200);
            json.setMsg("上传图片成功！！！");
            json.setData(fileNewName);
        } catch (IOException e) {
            json.setCode(500);
            json.setMsg("上传图片失败！！！");
            json.setData(null);
            throw new RuntimeException(e);
        }
        return json;
    }
}
